<?php

namespace App\Kuafu\Wechat\Service\H5;

use App\Kuafu\Base\Service\BaseService;
use App\Kuafu\Wechat\Service\WechatCallbackService;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;


// 微信被动回复消息
class H5Service
{
    public function getWxConfig(array $params)
    {
        $jsapiTicketResult = self::getJsapiTicket();

        $appid     = config('wechat.publicAppid');
        $timestamp = time();
        $nonceStr  = Str::random();

//        $nonceStr          = 'Wm3WZYTPz0wzccnW';
//        $jsapiTicketResult = 'sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg';
//        $timestamp         = '1414587457';
//        $params[]     = '';
        $signatureArr = [
            'noncestr'     => $nonceStr,
            'jsapi_ticket' => $jsapiTicketResult, // 前端字段统一
            'timestamp'    => $timestamp,
            'url'          => ($params['url'])
        ];


        ksort($signatureArr);

        $signature = sha1(urldecode(http_build_query($signatureArr)));

        unset($signatureArr['jsapi_ticket']);
        return $signatureArr + [
                'appId'     => $appid,
                'signature' => $signature
            ];
    }

    public function getJsapiTicket()
    {
        return Cache::remember('getJsapiTicket:1:', 3600, function () {

            try {
                $token = WechatCallbackService::getAccessToken();
                $token = $token['access_token'];
//            $token = '70_ZBGEfKdNPMu9wcb1TF9JoMP9-KK9rNZa2SwSR0x6IfQKFhKJe2UiJeIOSDNV4oi2igWmsQzLP6WKjXYZrPym2g8rWAzNFau9R5UzDtCT7LYVO9KWnszpHfUE8YYMWMaAAAEOE';

                $jsapiTicketResult = file_get_contents("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$token}&type=jsapi");

                $jsapiTicketResult = json_decode($jsapiTicketResult, 1);

                return $jsapiTicketResult['ticket'];
            } catch (\Exception $exception) {

                return '';
            }

        });
    }
}
